package cn.smbms.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;

import cn.smbms.pojo.User;
import cn.smbms.service.UserService;
import cn.smbms.tools.Constants;

@Controller
public class LoginController {
	@Autowired
	private UserService userService;
	
	
	@RequestMapping(value="/login",method=RequestMethod.GET) 
	public String login(){
		return "login";
	}
	
	@RequestMapping(value="login",method=RequestMethod.POST) 
	public String doLogin(User user,HttpSession session,HttpServletRequest request){
		User userLogin=userService.login(user);
		if(null!=userLogin) {//登录成功
			//放入session
			session.setAttribute(Constants.USER_SESSION, userLogin);
			//页面跳转
			return "frame";
		}else {
			//页面跳转 带出信息--转发
			request.setAttribute("error", "用户名和密码不正确");
			return "login";
		}
		
	}   
	//修改密码1
	@RequestMapping(value="pwdmodify",method=RequestMethod.GET)
	public String updatePassword(HttpServletRequest request,HttpSession session) {
		User user=userService.selectUserById(((User)session.getAttribute(Constants.USER_SESSION)).getId());
		request.setAttribute("user", user);
		return "pwdmodify";
	}
	//修改密码2
	@RequestMapping(value="pwdmodify",method=RequestMethod.POST)
	public String pwdmodify(User user,HttpSession session) {
		//String cjson="";
		int i=userService.updatePassword(((User)session.getAttribute(Constants.USER_SESSION)).getId(),user.getUserPassword());
		if(i>0) {
			//cjson=JSON.toJSONString(user);
			return "redirect:login";
		}else {
			return "pwdmodify";
		} 
	}
	//修改密码的校验
	@RequestMapping(value="check",produces= {"application/json;charset=UTF-8"})
	@ResponseBody
	public Object checkPassword(@RequestParam("oldPassword")String oldPassword,HttpSession session) {
		Object o=session.getAttribute(Constants.USER_SESSION);
		String password=((User)o).getUserPassword();
		Map<String, String> resultMap = new HashMap<String, String>();
		
		if(null == o ){//session过期
			resultMap.put("result", "sessionerror");
		}else if(StringUtils.isNullOrEmpty(oldPassword)){//旧密码输入为空
			resultMap.put("result", "error");
		}else{  
			String sessionPwd = ((User)o).getUserPassword();
			if(oldPassword.equals(password)){
				resultMap.put("result", "true");
			}else{//旧密码输入不正确
				resultMap.put("result", "false");
			}
		}
		
		return JSONArray.toJSON(resultMap);
	}
}
